package Algorithm.DataStruct.Stack;

import java.util.Deque;
import java.util.LinkedList;

//https://leetcode-cn.com/problems/simplify-path/
//71. 简化路径
public class Leetcode71_简化路径 {
    class Solution {
        public String simplifyPath(String path) {
            path = path + "/";
            Deque<String> stack = new LinkedList<String>();
            int i = 0;
            int start = 0;
            while(i < path.length()){
                if(path.charAt(i) == '/'){
                    if(start != i){
                        String fileName = path.substring(start, i);
                        if("..".equals(fileName)){
                            if(!stack.isEmpty()){
                                stack.removeLast();
                            }
                        }else if(".".equals(fileName)){

                        }else{
                            stack.addLast(fileName);
                        }
                    }

                    start = i + 1;
                }
                i++;
            }

            StringBuilder builder = new StringBuilder();
            if(stack.size() == 0){
                return "/";
            }

            while(!stack.isEmpty()){
                builder.append("/").append(stack.removeFirst());
            }

            return builder.toString();
        }
    }
}
